define(function() {

    return {
        init: function() {
            var self = this;
            FB.api('me/friends', {fields: 'name'}, function(res) {
                if(res && res.data) {
                    self.friends = res.data;
                    if(self.input.val().length) {
                        self.search();
                    }
                }
            });
            
            this.listen();
        },
        listen: function() {
            this.input = $('#search').on('keyup', $.proxy(this.search, this));
            
            this.input.on('blur', function() {
                $('.typeahead').delay(100).fadeOut('fast', function() {
                    $(this).remove();
                });
                $(this).val('');
            });
        },
        search: function(e) {
            if(e.which && e.which == 27) {
                return this.input.blur();
            }
            
            var text = $.trim(this.input.val());
            if(!this.friends || !text) { return; }
            
            var items = [];
            $.each(this.friends, function() {
                if(this.name.toLowerCase().indexOf(text) == 0) {
                    items.push(this);
                }
            });
            
            if(items && items.length) {
                this.results(items.slice(0,10));
            }
        },
        results: function(items) {
            $('.typeahead').remove();
            
            var typeahead = $('<ul />').addClass('typeahead');
            $.each(items, function() {
                $('<li />').html('<a href="#' + this.id + '">' + this.name + '</a>').appendTo(typeahead);
            });
            
            typeahead.appendTo(document.body);
        }
    };
});